package com.chushouya.order.service.api.impl;

import com.chushouya.order.dto.api.shunfeng.*;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Strings;
import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.dao.entity.ExpressLogEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderLogisticsEntity;
import com.chushouya.order.dao.repository.ExpressLogRepository;
import com.chushouya.order.dao.repository.OrderLogisticsRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.admin.action.OrderDeliveryAction;
import com.chushouya.order.dto.admin.action.OrderReceiveAction;
import com.chushouya.order.dto.admin.orderlogistics.OrderLogisticsQuery;
//=====order.dto.api.shunfeng.*;
import com.chushouya.order.dto.api.shunfeng.*;
import com.chushouya.order.service.admin.KefuOrderActionService;
import com.chushouya.order.service.api.ShunfengPushApiService;
import com.chushouya.order.service.common.OrderLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 顺丰推送API服务实现
 */
@Service
@Slf4j
public class ShunfengPushApiServiceImpl implements ShunfengPushApiService {


    @Resource
    private OrderLogisticsRepository orderLogisticsRepository;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderLogService orderLogService;

    @Resource
    private ExpressLogRepository expressLogRepository;

    @Resource
    private KefuOrderActionService kefuOrderActionService;

    private OrderLogisticsEntity getOrderLogistics(String expressNo){
        OrderLogisticsQuery query = new OrderLogisticsQuery();
        query.setExpressNo(expressNo);
        OrderLogisticsEntity orderLogisticsEntity = orderLogisticsRepository.selectOne(query);
        if (Objects.isNull(orderLogisticsEntity)){
            throw Ex.business("未找到订单物流信息");
        }
        return orderLogisticsEntity;
    }

    private OrderEntity getOrder(Long orderId){
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)){
            throw Ex.business("未找到订单信息");
        }
        return orderEntity;
    }

    /**
     * 保存物流轨迹记录
     */
    private void saveExpressLog(Long orderId, ShunfengWaybillRouteDTO route) {
        ExpressLogEntity expressLog = new ExpressLogEntity();
        expressLog.setOrderId(orderId);
        expressLog.setOrderCode(route.getOrderid());
        expressLog.setExpressNo(route.getMailno());
        expressLog.setAcceptAddress(route.getAcceptAddress());
        expressLog.setReasonName(route.getReasonName());
        expressLog.setOpCode(route.getOpCode());
        expressLog.setReasonCode(route.getReasonCode());
        expressLog.setRemark(route.getRemark());
        expressLog.setCreateTime(Dates.getTimeNow());
        expressLog.setUpdateTime(Dates.getTimeNow());
        
        expressLogRepository.insertSelective(expressLog);
        log.info("已保存物流轨迹记录 - 运单号: {}, 操作码: {}", route.getMailno(), route.getOpCode());
    }


    @Override
    public void handleOrderStatePush(ShunfengOrderStatePushDTO orderStatePushDTO) {
        log.info("开始处理顺丰订单状态推送，请求ID: {}", orderStatePushDTO.getRequestId());
        
        if (orderStatePushDTO.getOrderState() == null || orderStatePushDTO.getOrderState().isEmpty()) {
            log.warn("订单状态列表为空，跳过处理");
            return;
        }
        
        for (ShunfengOrderStateDTO orderState : orderStatePushDTO.getOrderState()) {
            try {
                processOrderState(orderState);
            } catch (Exception e) {
                log.error("处理订单状态失败，订单号: {}, 运单号: {} {}",
                        orderState.getOrderNo(), orderState.getWaybillNo(), e.getMessage());
            }
        }
        
        log.info("顺丰订单状态推送处理完成，请求ID: {}", orderStatePushDTO.getRequestId());
    }

    @Override
    public void handleRoutePush(ShunfengRoutePushDTO routePushDTO) {
        log.info("开始处理顺丰路由推送");
        
        if (routePushDTO.getBody() == null || 
            routePushDTO.getBody().getWaybillRoute() == null || 
            routePushDTO.getBody().getWaybillRoute().isEmpty()) {
            log.warn("路由信息列表为空，跳过处理");
            return;
        }
        
        for (ShunfengWaybillRouteDTO route : routePushDTO.getBody().getWaybillRoute()) {
            try {
                processWaybillRoute(route);
            } catch (Exception e) {
                log.error("处理路由信息失败，运单号: {}, 订单ID: {} {}",
                        route.getMailno(), route.getOrderid(), e.getMessage());
            }
        }
        
        log.info("顺丰路由推送处理完成");
    }

    @Override
    public void handleFreightPush(ShunfengFreightPushDTO freightPushDTO) {
        log.info("开始处理顺丰运费推送");
        
        if (freightPushDTO.getFreightData() == null) {
            log.warn("运费数据为空，跳过处理");
            return;
        }
        
        ShunfengFreightPushDTO.ShunfengFreightDataDTO freightData = freightPushDTO.getFreightData();
        
        try {
            processFreightData(freightData);
        } catch (Exception e) {
            log.error("处理运费数据失败，运单号: {} {}", freightData.getWaybillNo(),e.getMessage());
        }
        
        log.info("顺丰运费推送处理完成");
    }
    
    /**
     * 处理运费数据
     */
    private void processFreightData(ShunfengFreightPushDTO.ShunfengFreightDataDTO freightData) {
        log.info("处理运费数据 - 运单号: {}, 计费重量: {}",
                freightData.getWaybillNo(), freightData.getMeterageWeightQty());
        
        OrderLogisticsEntity orderLogistics = getOrderLogistics(freightData.getWaybillNo());
        OrderEntity order = getOrder(orderLogistics.getOrderId());
        final Long orderId = order.getOrderId();
        
        // 计算总费用
        Double totalFee = 0.0;
        if (freightData.getFeeList() != null && !freightData.getFeeList().isEmpty()) {
            for (ShunfengFeeDTO fee : freightData.getFeeList()) {
                if (fee.getFeeAmt() != null) {
                    totalFee += fee.getFeeAmt();
                }
            }
        }
        
        // 记录运费信息到订单日志
        String logMessage = Strings.format("运费推送 - 计费重量: {}kg, 总费用: {}元", 
                freightData.getMeterageWeightQty(), totalFee);
        orderLogService.addOrderActionLog(orderId,"系统", OrderActionEnum.FOLLOW_ORDER.value(), logMessage);

    }

    /**
     * 处理单个订单状态
     */
    private void processOrderState(ShunfengOrderStateDTO orderState) {
        log.info("处理订单状态 - 订单号: {}, 运单号: {}, 状态码: {}, 状态描述: {}, 更新时间: {}", 
                orderState.getOrderNo(), orderState.getWaybillNo(), 
                orderState.getOrderStateCode(), orderState.getOrderStateDesc(), 
                orderState.getLastTime());
        OrderLogisticsEntity orderLogistics = getOrderLogistics(orderState.getWaybillNo());
        OrderEntity order = getOrder(orderLogistics.getOrderId());
        final Long orderId = order.getOrderId();

        orderLogService.addOrderActionLog(orderId,"系统", OrderActionEnum.FOLLOW_ORDER.value(),
                Strings.format("状态码: {}, 状态描述: {}",
                        orderState.getOrderStateCode(),
                        orderState.getOrderStateDesc()));
//        OrderEntity updateOrder = new OrderEntity();
//        updateOrder.setOrderId(order.getOrderId());
//        updateOrder.setLogisticsStatus(LogisticsTypeEnum.USER_SEND.value());
//        updateOrder.setDeliveryTime(Dates.getTimeNow());
//        orderRepository.updateByPrimaryKeySelective(updateOrder);

        handleSpecificOrderState(orderState);
    }

    /**
     * 处理单个路由信息
     */
    private void processWaybillRoute(ShunfengWaybillRouteDTO route) {
        log.info("处理路由信息 - 运单号: {}, 订单ID: {}, 操作码: {}, 收件时间: {}, 地址: {}", 
                route.getMailno(), route.getOrderid(), route.getOpCode(), 
                route.getAcceptTime(), route.getAcceptAddress());
        OrderLogisticsEntity orderLogistics = getOrderLogistics(route.getMailno());
        OrderEntity order = getOrder(orderLogistics.getOrderId());
        final Long orderId = order.getOrderId();

        orderLogService.addOrderActionLog(orderId,"系统", OrderActionEnum.FOLLOW_ORDER.value(),
                route.getRemark());
        
        // 记录详细的物流轨迹到ExpressLog表
        saveExpressLog(orderId, route);
        
        // 根据操作码处理特定逻辑
        // 例如：50 收件，80 派件等
        handleSpecificRouteOperation(route);
    }

    /**
     * 处理特定的订单状态
     */
    private void handleSpecificOrderState(ShunfengOrderStateDTO orderState) {
        String stateCode = orderState.getOrderStateCode();
        
        switch (stateCode) {
            case "04-40001":
                // 调度成功+收派员信息
                log.info("订单调度成功，收派员: {}, 电话: {}", 
                        orderState.getEmpCode(), orderState.getEmpPhone());
                // TODO: 通知用户收派员信息
                break;
                
            case "04-40037":
                // 下单已接收
                log.info("订单已被顺丰接收: {}", orderState.getOrderNo());
                // TODO: 更新订单状态为已发货
                break;
                
            default:
                log.debug("处理其他订单状态: {}", stateCode);
                break;
        }
    }

    /**
     * 处理特定的路由操作
     */
    private void handleSpecificRouteOperation(ShunfengWaybillRouteDTO route) {
        String opCode = route.getOpCode();
        OrderLogisticsEntity orderLogistics = getOrderLogistics(route.getMailno());
        Long orderId = orderLogistics.getOrderId();
        
        switch (opCode) {
            case "50":
                // 收件 - 调用deliveryOrder
                log.info("包裹已收件，运单号: {}，订单ID: {}", route.getMailno(), orderId);
                try {
                    OrderDeliveryAction deliveryAction = new OrderDeliveryAction();
                    deliveryAction.setOrderId(orderId);
                    deliveryAction.setActionNote("顺丰已收件 - " + route.getRemark());
                    kefuOrderActionService.deliveryOrder(deliveryAction);
                    log.info("已调用deliveryOrder处理收件状态，订单ID: {}", orderId);
                } catch (Exception e) {
                    log.error("调用deliveryOrder失败，订单ID: {} {}", orderId, e.getMessage());
                }
                break;
                
            case "80":
                // 派件/签收 - 调用orderReceive
                log.info("包裹正在派件/已签收，运单号: {}，订单ID: {}", route.getMailno(), orderId);
                try {
                    OrderReceiveAction receiveAction = new OrderReceiveAction();
                    receiveAction.setOrderId(orderId);
                    receiveAction.setActionNote("顺丰派件/签收 - " + route.getRemark());
                    kefuOrderActionService.orderReceive(receiveAction);
                    log.info("已调用orderReceive处理签收状态，订单ID: {}", orderId);
                } catch (Exception e) {
                    log.error("调用orderReceive失败，订单ID: {} {}", orderId, e.getMessage());
                }
                break;
                
            default:
                log.debug("处理其他路由操作: {}，订单ID: {}", opCode, orderId);
                break;
        }
    }
}
